package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Md5Util;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static cn.wolfcode.wolf2w.domain.UserInfo.STATE_NORMAL;
import static cn.wolfcode.wolf2w.util.RedisKeys.VERIFY_CODE;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository repository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /*@Value("${user.appkey}")
    private String appkey;
    @Value("${user.url}")
    private String url;*/

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }


    @Override
    public boolean checkPhone(String phone) {
        // 如果 user为null，说明手机号码不存在，如果不为null，说明手机号码存在
        UserInfo user = repository.findByPhone(phone);
        return user != null;
    }

    @Override
    public void sendVerifyCode(String phone) {
        // 生成验证码
        String code = UUID.randomUUID().toString()
                .replace("-", "").substring(0, 4);
        // 生成短信
        /*StringBuilder sb = new StringBuilder();
        sb.append("【创信】你的验证码是：").append(code).append("，")
                            .append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内有效！");
        String content = sb.toString();
        // 发送短信
        //https://way.jd.com/chuangxin/VerCodesms?mobile={1}&content={2}&appkey={3}
        String url = "https://way.jd.com/chuangxin/VerCodesms?mobile={1}&content={2}&appkey={3}";
        RestTemplate rest = new RestTemplate();
        // 第一个参数是 URL， 第二个参数放回值接收的类型，
        String ret = rest.getForObject(url,
                String.class,phone,content,appkey);
        System.out.println(ret);
        if (!ret.contains("查询成功")){
            throw new LogicException("发送验证码失败");
        }*/
        // 把验证码和手机号码存入到 Redis 中
        System.out.println(code);
        userInfoRedisService.saveCode(phone,code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        // 判断传入的参数是否有长度，前端和后端都验证，双重保险
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        // 2次密码是否一致
        AssertUtil.isEquals(password,rpassword,"密码和确认密码不一致");
        // 手机号码的格式是否正确
        if (!AssertUtil.isPhoneNum(phone)) {
            throw new LogicException("手机号码格式不正确");
        }
        // 手机号码是否唯一
        if (this.checkPhone(phone)) {
            throw new LogicException("手机号码已存在");
        }
        // 短信验证码是否一致
        String key = VERIFY_CODE.join(phone);
        String code = userInfoRedisService.getCode(key);
        if (!verifyCode.equals(code)){
            throw new LogicException("验证码不正确");
        }
        // 注册
        UserInfo user = new UserInfo();
        user.setPhone(phone);
        user.setNickname(nickname);
        String mdPassword = Md5Util.encodeByMD5(password);
        user.setPassword(mdPassword);
        user.setEmail("");
        user.setCity("");
        user.setHeadImgUrl("/images/default.jpg");
        user.setInfo("");
        user.setState(STATE_NORMAL);
        repository.save(user);
    }

    @Override
    public Map login(String username, String password) {
        AssertUtil.hasLength(username,"用户名不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        String mdPassword = Md5Util.encodeByMD5(password);
        // 判断用户名
        UserInfo user = repository.findByPhone(username);
        if (user == null || !user.getPassword().equals(mdPassword)){
            throw new LogicException("用户名或密码错误");
        }
        // 存入到Redis缓存中
        String token = UUID.randomUUID().toString().replace("-","");
        userInfoRedisService.addToken(token, JSON.toJSONString(user));
        // 响应 token 和 user 到前端浏览器
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return map;
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public List<UserInfo> queryCity(String keyword) {
        return repository.findByCity(keyword);
    }
}
